<template>
  <div class="stock-query">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="商品编码">
            <el-input v-model="searchForm.productCode" placeholder="请输入商品编码" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable style="width: 120px">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column prop="productCode" label="商品编码" width="120" />
        <el-table-column label="商品图片" width="160">
          <template #default="{ row }">
            <el-image :src="row.imageUrl" :preview-src-list="[row.imageUrl]" preview-teleported fit="contain"
              style="width: 100%; height: 100%">
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="200" />
        <el-table-column prop="specifications" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouseId" label="所在仓库" width="100" align="center">
          <template #default="scope">
            <span>{{ getWarehouseName(scope.row.warehouseId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存数量" width="100" align="center" />
        <el-table-column label="进价" align="center">
          <template #default="scope">
            ¥{{ formatAmount(scope.row.purchasePrice) }}
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center">
          <template #default="scope">
            <span style="color: #dc3545;">¥{{ formatAmount(scope.row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预警状态" width="100">
          <template #default="scope">
            <el-tag :type="getStockStatusType(scope.row)">
              {{ getStockStatusLabel(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间"  align="center">
          <template #default="scope">
            {{ (scope.row.createDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作"  fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleOut(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 出库数量选择对话框 -->
    <el-dialog v-model="outboundVisible" title="编辑" width="500px">
      <el-form :model="outboundForm" label-width="100px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品编码">{{ outboundForm.productCode }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ outboundForm.productName }}</el-descriptions-item>
          <el-descriptions-item label="当前库存">{{ outboundForm.currentQuantity }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ outboundForm.specifications }}</el-descriptions-item>
        </el-descriptions>
        
        <el-form-item label="库存数量" style="margin-top: 20px;">
          <el-input-number 
            v-model="outboundForm.quantity" 
            :min="1" 
            :precision="0"
            style="width: 200px;"
          />
        </el-form-item>
        
   
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outboundVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmOutbound" :loading="outboundLoading">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, toRaw } from 'vue'
import { ElMessage,ElMessageBox} from 'element-plus'
import { inventoryApi } from '../../api'

import { fetchWarehouseList } from '../../utils/commonMethods';
// 仓库列表
const warehouseList = ref([]);
// 获取仓库列表
const getWarehouseList = async () => {
  warehouseList.value = await fetchWarehouseList();
};
// 搜索表单
const searchForm = reactive({
  productCode: '',
  productName: '',
  warehouseId: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取仓库名称
const getWarehouseName = (warehouseId) => {
  const warehouse = warehouseList.value.find(item => item.id === warehouseId)
  return warehouse ? warehouse.warehouseName : ''
}

// 获取表格数据
const getTableData = async () => {
  const params = {
    current: currentPage.value,
    size: pageSize.value,
    ...searchForm
  }
  loading.value = true
  try {
    let { data } = await inventoryApi.getList(params)
    console.log('data', data);
    let list = data.records || []
    total.value = data.total;

    list.forEach(item=>{
      item.imageUrl = import.meta.env.VITE_API_URL + item.imageUrl
    })
    tableData.value = list
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 库存状态
const getStockStatusType = (row) => {
  if (row.quantity <= 0) return 'danger'
  if (row.quantity <= 10) return 'warning'
  return 'success'
}

const getStockStatusLabel = (row) => {
  if (row.quantity <= 0) return '无库存'
  if (row.quantity <= 10) return '低库存'
  return '正常'
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.productCode = ''
  searchForm.productName = ''
  searchForm.warehouseId = ''
  handleSearch()
}

// 出库相关数据
const outboundVisible = ref(false)
const outboundLoading = ref(false)
const outboundForm = reactive({
  id: '',
  productCode: '',
  productName: '',
  currentQuantity: 0,
  specifications: '',
  quantity: 1,
})

const currentRow = ref(null)
// 修改原来的 handleOut 方法
const handleOut = (row) => {
  outboundForm.id = row.id
  outboundForm.productCode = row.productCode
  outboundForm.productName = row.productName
  outboundForm.currentQuantity = row.quantity
  outboundForm.specifications = row.specifications
  outboundForm.purchasePrice = row.purchasePrice
  outboundForm.quantity = row.quantity
  outboundForm.remark = ''
  currentRow.value = row
  outboundVisible.value = true

}

// 确认出库
const confirmOutbound = async () => {
  try {
    outboundLoading.value = true
  
    // 调用出库 API
    await inventoryApi.update(currentRow.value)
  
    ElMessage.success('编辑成功')
    outboundVisible.value = false
    getTableData() // 刷新列表
  } catch (error) {
    if (error !== "cancel") {
      console.error("编辑失败:", error)
      ElMessage.error(error.message || "编辑失败")
    }
  } finally {
    outboundLoading.value = false
  }
}

const handleDelete = async (row) => {
  //是否删除
  try {
    await ElMessageBox.confirm("确认删除该入库单吗？", "提示", {
      type: "warning",
    });
    await inventoryApi.delete(row.id);
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error(error.message || "删除失败");
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === undefined || amount === null || isNaN(amount)) {
    return '0.00'
  }
  return Number(amount).toFixed(2)
}

// 初始化
onMounted(() => {
  getWarehouseList()
  getTableData()
})
</script>

<style scoped>
.stock-query {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-tabs {
  margin-top: 20px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

.detail-table {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>